package com.oracle.controller;

import com.oracle.pojo.Admin;
import com.oracle.pojo.News;
import com.oracle.pojo.NewsType;
import com.oracle.pojo.User;
import com.oracle.service.AdminService;
import com.oracle.service.NewsService;
import com.oracle.service.NewsTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private NewsTypeService newsTypeService;

    @RequestMapping(value = "/adminLogin",method = RequestMethod.POST)
    public String adminLogin(HttpSession session, String name, String password) {
        Admin admin = adminService.getAdminByNameAndPwd(name, password);
        session.setAttribute("admin",admin);
        return "admin/admin";
    }

    @RequestMapping(value = "/newsMgr",method = RequestMethod.GET)
    public String newsList(Model model) {
        List<News> newsList = newsService.getAllNews();
        model.addAttribute("newsList",newsList);
        return "admin/news_manager";
    }

    @RequestMapping(value = "/newsDelete/{id}",method = RequestMethod.GET)
    public String deleteNews(@PathVariable Integer id) {
        newsService.deleteNewsById(id);
        return "redirect:/newsMgr";
    }

    @RequestMapping(value = "/newstypeMgr",method = RequestMethod.GET)
    public String newstypeList(Model model) {
        List<NewsType> newsTypeList = newsTypeService.getAllNewsType();
        model.addAttribute("newsTypeList",newsTypeList);
        return "admin/newstype_manager";
    }

    @RequestMapping(value = "/deleteNewsType/{id}",method = RequestMethod.GET)
    public String deleteNewsType(@PathVariable Integer id) {
        newsTypeService.deleteNewsById(id);
        return "redirect:/newstypeMgr";
    }

    @RequestMapping(value = "/addNewsType",method = RequestMethod.GET)
    public String addNewsType(NewsType newsType) {
        newsTypeService.addNewsType(newsType);
        return "redirect:/newstypeMgr";
    }

    @RequestMapping(value = "/to/existAdmin",method = RequestMethod.GET)
    public String userLoginExist(HttpSession session) {
        session.removeAttribute("admin");
        session.invalidate();
        return "redirect:/";
    }
}
